use serde::{Deserialize, Deserializer, Serialize, Serializer};

#[derive(Serialize, Deserialize, Debug)]
struct Person {
    name: String,
    age: u8,
    email: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct Config {
    username: String,
    #[serde(skip_serializing)]
    password: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct User {
    #[serde(rename = "userName")]
    username: String,
    age: u8,
}

// 批量重命名所有字段或变体 case可以是 lowercase、UPPERCASE、PascalCase、camelCase、snake_case、kebab-case 等
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
struct MyStruct {
    firstName: String,
    lastName: String,
}

// 反序列化时，如果字段缺失，则使用该字段的默认值
#[derive(Serialize, Deserialize)]
struct OptionalStruct {
    id: u32,
    #[serde(default)]
    optional_field: String,
}

pub fn test() {
    let person = Person {
        name: String::from("Alice"),
        age: 30,
        email: String::from("alice@example.com"),
    };
    // 序列化为 JSON 字符串
    let json_string = serde_json::to_string(&person).unwrap();
    println!("Serialized JSON: {}", json_string);

    let json_data = r#"
       {
           "name": "Bob",
           "age": 25,
           "email": "bob@example.com"
       }
   "#;
    // 反序列化为 Person 结构体
    let person: Person = serde_json::from_str(json_data).unwrap();
    println!("Deserialized struct: {:?}", person);
}

// 通过实现 serde::Serialize 和 serde::Deserialize trait 来自定义序列化和反序列化逻辑
fn serialize_as_hex<S: Serializer>(x: &u32, s: S) -> Result<S::Ok, S::Error> {
    s.serialize_str(&format!("{:X}", x))
}

#[derive(Serialize, Deserialize)]
struct SelfSerial {
    #[serde(serialize_with = "serialize_as_hex")]
    id: u32,
}

// 
fn deserialize_from_hex<'de, D: Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
    let s = String::deserialize(d)?;
    u32::from_str_radix(&s, 16).map_err(serde::de::Error::custom)
}

#[derive(Serialize, Deserialize)]
struct SelfDeserial {
    #[serde(deserialize_with = "deserialize_from_hex")]
    id: u32,
}